package com.ciaojian.client.controller;

import cn.hutool.core.util.RandomUtil;
import com.ciaojian.client.service.RedpackSettingServiceImpl;
import com.ciaojian.client.service.SendRedpackRecordServiceImpl;
import com.ciaojian.core.base.annotation.ApiIdempotent;
import com.ciaojian.core.model.RedpackSetting;
import com.ciaojian.core.model.SendRedpackRecord;
import com.ciaojian.core.util.Result;
import com.ciaojian.core.util.UserUtil;
import com.ciaojian.pay.core.enums.SignType;
import com.ciaojian.pay.wxpay.WxPayApi;
import com.ciaojian.pay.wxpay.enums.code.RedPackCode;
import com.ciaojian.pay.wxpay.model.bean.WxBean;
import com.ciaojian.pay.wxpay.model.request.TransferModel;
import com.ciaojian.pay.wxpay.model.response.TransferResponse;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Map;

/**
 * @author oxiny
 */
@Slf4j
@Api(tags = "微信红包")
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/redpack-record")
public class CouponGrantRecordController {
    private final SendRedpackRecordServiceImpl sendRedpackRecordService;
    private final WxBean wxBean;
    private final RedpackSettingServiceImpl redpackSettingService;


    @ApiOperation("获取用户未领的红包")
    @GetMapping
    public Result get(@NotNull Integer userId) {
        return Result.ok(sendRedpackRecordService.lambdaQuery()
                .eq(SendRedpackRecord::getUserId, userId)
                .eq(SendRedpackRecord::getStatus, 0)
                .list());
    }

    @ApiIdempotent
    @ApiOperation("领取红包")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "红包发送记录", paramType = "query")
    })
    @PutMapping("/receive")
    public Result receiveRedPack(@NotNull Integer id) {
        SendRedpackRecord sendRedpackRecord = sendRedpackRecordService.getById(id);
        RedpackSetting redpackSetting = redpackSettingService.getById(1);
        Map<String, Object> params = TransferModel.builder()
                .nonce_str(RandomUtil.randomString(32))
                .mchid(wxBean.getMchId())
                .mch_appid(wxBean.getAppId())
                .partner_trade_no(sendRedpackRecord.getMchBillNo())
                .openid(UserUtil.getOpenId(sendRedpackRecord.getUserId()))
                .check_name(TransferModel.CheckType.NO_CHECK)
                .amount(String.valueOf(redpackSetting.getTotalAmount()))
                .desc(redpackSetting.getRemark())
                .spbill_create_ip("116.22.134.182")
                .build()
                .createSign(wxBean.getAppSecret(), SignType.MD5, false);
        TransferResponse response = WxPayApi.transfers(params, wxBean.getCertPath(), wxBean.getCertPass());

        if (response.getResult_code().equals(RedPackCode.FAIL.getCode())) {
            System.err.println(response.getErr_code() + ":" + response.getErr_code_des());
            log.info(response.getErr_code() + ":" + response.getErr_code_des());
        }

        sendRedpackRecord.setStatus(1)
                .setReceiveTime(new Date())
                .updateById();
        return Result.ok();
    }

}

